package com.swust.excel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.swust.excel.entity.LogInfo;
import com.swust.excel.support.DataSourceSupport;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.List;

/**
 * @author: Chen Yixing
 * @since: 2023/11/17 10:48:37
 * @description: 多sheet返回
 */
@RestController
@RequestMapping("/export/excel")
public class MorSheetController {
    private final DataSourceSupport dataSourceSupport;

    public MorSheetController(DataSourceSupport dataSourceSupport) {
        this.dataSourceSupport = dataSourceSupport;
    }

    /**
     * 导出多sheet案例
     */
    @GetMapping("/morSheet")
    public void exportMorSheet(HttpServletResponse response) throws Exception {
        List<LogInfo> logs = dataSourceSupport.initLogInfo();
        if (ObjectUtils.isEmpty(logs)) {
            dataSourceSupport.initFailResponse(response);
        } else {
            dataSourceSupport.initExcelResponse(response, LocalDate.now().toString());

            // 表一写入
            ExcelWriter writer = EasyExcel.write(response.getOutputStream(), LogInfo.class).build();
            WriteSheet sheet = EasyExcel.writerSheet(0, "基础信息").build();
            writer.write(logs, sheet);

            // 表二写入
            WriteSheet sheet2 = EasyExcel.writerSheet(1, "详细信息").head(LogInfo.class).build();
            writer.write(logs, sheet2);

            // 关闭流，response返回excel流
            writer.finish();
        }
    }

}
